package com.gs.coursera.algorithms.core.graph;

import java.io.BufferedReader;
import java.io.IOException;

public class PathGraph extends UndirectedGraph<Integer, Integer> {

	private Integer[] weights;
	
	public PathGraph(BufferedReader reader) throws IOException {
		super(reader);
		weights = new Integer[getVertexCount()];
		String line = reader.readLine();
		String[] weightVals = line.split(" ");
		for (int i = 0; i < weightVals.length; i++) {
			weights[i] = Integer.parseInt(weightVals[i].trim());
		}
		while((line = reader.readLine()) != null){
			String[] data = line.split(" ");
			Integer e1 = Integer.parseInt(data[0].trim());
			Integer e2 = Integer.parseInt(data[1].trim());
			addEdge(e1, e2, 0);
		}
	}


	@Override
	public void addEdge(Integer valueOne, Integer valueTwo, Integer weight) {
		Vertex<Integer, Integer> v1 = null;
		Vertex<Integer, Integer> v2 = null;
		if(null != getVertices().get(valueOne-1)){
			v1 = getVertices().get(valueOne - 1);
		} else {
			v1 = new Vertex<Integer, Integer>(valueOne);
			v1.setVertexNumber(valueOne - 1);
			v1.setWeight(weights[valueOne - 1]);
			getVertices().set(valueOne-1, v1);
		}
		if(null != getVertices().get(valueTwo-1)){
			v2 = getVertices().get(valueTwo - 1);
		} else {
			v2 = new Vertex<Integer, Integer>(valueTwo);
			v2.setVertexNumber(valueTwo - 1);
			v2.setWeight(weights[valueOne - 1]);
			getVertices().set(valueTwo-1, v2);
		}
		if(null != v1 && null != v2){
			Edge<Integer, Integer> edge = new Edge<Integer, Integer>(v1, v2, weight);
			v1.addAdjacentEdge(edge);
			getEdges().add(edge);
			Edge<Integer, Integer> edgeRev = new Edge<Integer, Integer>(v2, v1, weight);
			v2.addAdjacentEdge(edgeRev);
		}
	}
}
